﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using Microsoft.Win32;
using TinyEngine.Core.Services;
using System.IO;
using System.Windows.Data;
using TinyEngine.Editor.Extensibility;

namespace TinyEngine.Editor.DefaultPlugins.AssetExplorer
{
    class AssetExplorerPlugin : IPlugin
    {
        public void Initialize()
        {
            foreach (var item in EditorSession.Instance.MainMenu.Items)
            {
                var itm = item as MenuItem;
                if (itm.Name == "menuProject")
                {
                    /*
                    var newItem = new MenuItem()
                    {
                        Header = "Asset Explorer"
                    };
                    itm.Items.Add(newItem);
                    newItem.Click += new System.Windows.RoutedEventHandler(AssetExplorer_Click);
                    */
                    var newItem = new MenuItem()
                    {
                        Header = "Add Asset"
                    };
                    //newItem.SetBinding(MenuItem.IsEnabledProperty, new Binding("HasSceneOpen"));
                    newItem.Click += new System.Windows.RoutedEventHandler(AddNewAsset_Click);
                    itm.Items.Add(newItem);
                }
            }
        }

        void AddNewAsset_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Multiselect = true; 
            dialog.ShowDialog();
            
            if (string.IsNullOrEmpty(dialog.FileName))
            {
                return;
            }

            if (dialog.FileNames.Length > 0)
            {
                foreach (var item in dialog.FileNames)
                {
                    AddAsset(item);
                }

                EditorSession.Instance.FireAssetsAdded();
            }
        }

        private void AddAsset(string item)
        {
            var assets = ServiceManager.GetService<AssetLibrary>();
            var name = Path.GetFileNameWithoutExtension(item);
            var content =Path.GetFullPath(Path.Combine(EditorSession.Instance.RootPath, EditorSession.Instance.ActiveProject.ContentPath));
            var relativeLoc = item.Replace(content, "");
            if (relativeLoc.StartsWith("\\"))
                relativeLoc = relativeLoc.Substring(1);

            assets.AddSprite(name, relativeLoc, true);

        }

        void AssetExplorer_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            
        }

        public CreateUserControlResponde CreateInEditorControl()
        {
            return null;
        }
    }
}
